# coding=utf8
import json
import time
import falcon
from bson import ObjectId

from libs.help import stream_to_params, time_to_str
from models.resource.ad import model_res_ad
from logging import getLogger

from models.resource.classify import model_res_classify
from models.user.ad import model_user_ad

logger = getLogger('base')


class AdsResource:
    def on_options(self, req, resp, cid):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_get(self, req, resp, cid):
        uid = req.get_header('uid')

        data = model_res_ad.coll.find({
            'ClassifyId': ObjectId(cid),
            'Uid': ObjectId(uid)
        })
        ads = []
        for item in data:
            ads.append({
                'id': str(item['_id']),
                'title': item['Title'],
                'time_str': item['UpdateStr']
            })
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.body = json.dumps({
            'info': {
                'code': 200
            },
            'item': ads
        })


class AdContentResource:
    def on_options(self, req, resp, cid, aid):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_get(self, req, resp, cid, aid):
        data = model_res_ad.coll.find_one({
            '_id': ObjectId(aid)
        })
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.body = json.dumps({
            'info': {
                'code': 200
            },
            'item': {
                'title': data['Title'],
                'content': data['Content']
            }
        })

    def on_post(self, req, resp, cid, aid):
        data = req.stream.read().decode()
        data = stream_to_params(data)

        uid = req.get_header('uid')

        if aid == '0':
            model_res_ad.coll.insert_one({
                'Title': data['title'],
                'Content': data['content'],
                'ClassifyId': ObjectId(cid),
                'Uid': ObjectId(uid),
                'Update': int(time.time()),
                'UpdateStr': time_to_str('%Y-%m-%d %H:%M')
            })
        else:
            model_res_ad.coll.update({'_id': ObjectId(aid)}, {
                '$set': {
                    'Title': data['title'],
                    'Content': data['content'],
                    'Update': int(time.time()),
                    'UpdateStr': time_to_str('%Y-%m-%d %H:%M')
                }
            })
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.body = json.dumps({
            'info': {
                'code': 200
            }
        })


class BandAdResource:
    def on_options(self, req, resp, appid):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_get(self, req, resp, appid):
        uid = req.get_header('uid')

        band_ads = model_user_ad.coll.find({
            'appid': appid
        })
        band_ads_list = dict()
        for ad in band_ads:
            band_ads_list[str(ad['ClassifyId'])] = str(ad['AdId'])

        ads_list = model_res_ad.coll.find({
            'Uid': ObjectId(uid)
        })
        ads = dict()
        for ad in ads_list:
            classify_id = str(ad['ClassifyId'])
            if classify_id not in ads:
                ads[classify_id] = []
            ads[classify_id].append({
                'ad_id': str(ad['_id']),
                'ad_title': ad['Title']
            })
        classify_list = model_res_classify.coll.find()
        res = []
        for classify in classify_list:
            classify_id = str(classify['_id'])
            res.append({
                'classify_name': classify['ClassifyName'],
                'classify_id': classify_id,
                'band_ad_id': band_ads_list[classify_id] if classify_id in band_ads_list else 0,
                'ads': ads[classify_id] if classify_id in ads else []
            })
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.body = json.dumps({
            'info': {
                'code': 200
            },
            'item': res
        })

    def on_post(self, req, resp, appid):
        data = req.stream.read().decode()
        # 容错
        if not data:
            resp.status = falcon.HTTP_200  # This is the default status
            resp.set_header('Access-Control-Allow-Origin', '*')
            resp.set_header('Access-Control-Allow-Methods', 'POST')
            resp.set_header('Access-Control-Allow-Headers', 'uid')
            resp.body = json.dumps({
                'info': {
                    'code': 200
                }
            })
            return False
        data = stream_to_params(data)

        band_list = []
        for classify_id, ad_id in data.items():
            # 根据广告id,去获取广告title
            # todo 其实可以直接传过来
            ad = model_res_ad.coll.find_one({
                '_id': ObjectId(ad_id)
            })

            band_list.append({
                'ClassifyId': ObjectId(classify_id),
                'AdId': ObjectId(ad_id),
                'AdTitle': ad['Title'],
                'appid': appid
            })

        model_user_ad.coll.insert_many(band_list)

        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.body = json.dumps({
            'info': {
                'code': 200
            }
        })
